<template>
  <div class="add-box">
    <div v-if="popData[propKey] && !fileList.length" class="img-box">
      <img width="100%" height="100%" :src="popData[propKey]" alt="">
    </div>
    <el-upload
      ref="upload"
      list-type="picture-card"
      action=""
      :on-change="handleChange"
      :file-list="fileList"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :limit="1"
      accept="image/*"
    >
      <i class="el-icon-plus" />
      <div slot="tip" class="el-upload__tip">
        <span>{{ tip || '请上传jpg/png文件，且不超过 5MB' }}</span>
      </div>
    </el-upload>
    <el-dialog>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'AddImg',
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: null
    },
    defaultFileList: {
      type: Array,
      default: () => []
    },
    // 字段配置
    propKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: ''
    }
  },
  created() {
    if (this.defaultFileList.length > 0) {
      this.fileList = this.defaultFileList.map(item => {
        return { url: item }
      })
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
    },
    // 进度：percentage
    // status：ready uploading success fail
    handleChange(file, fileList) {
      file.status = 'ready'
      this.fileList = fileList
      this.$emit('changeImg', this.propKey, this.fileList?.length ? this.fileList[0] : null)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  display: flex;
  padding-bottom: 10px;

  ::v-deep .el-upload-list {
    .el-upload-list__item-name {
      display: flex;
    }
  }

  .img-box {
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    line-height: 146px;
    vertical-align: top;
    margin-right: 20px;
  }
}
</style>
